package com.aofeng.hybridwork.android.task;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import com.aofeng.hybrid.activity.HybridActivity;
import com.aofeng.hybrid.service.EntityService;
import com.aofeng.hybrid.service.SqlService;
import com.aofeng.hybridwork.application.HybridApplication;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载安检计划异步任务
 * Created by LGY on 2016-08-25.
 */
public class DownloadAsyncTask extends AsyncTask<String, String, Boolean> {
    HybridActivity hybridActivity;
    //计划在客户端的序号，回调用
    String index;
    JSONObject param;

    public DownloadAsyncTask(HybridActivity hybridActivity) {
        this.hybridActivity = hybridActivity;
    }

    @Override
    /**
     * params:
     * 下载的url
     */
    protected Boolean doInBackground(String... params) {
        try {
            index = params[1];
            param = new JSONObject(params[0]);

            URL url = new URL(HybridApplication.BASE_URL + "/db/hql");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput( true );
            conn.setInstanceFollowRedirects( false );
            conn.setRequestMethod( "POST" );
            conn.setRequestProperty( "Content-Type", "text/plain");
            conn.setRequestProperty( "charset", "utf-8");
            String data = " from t_handplan t left join  fetch t.userfile where t.f_meterbook_id='" + param.getString("f_meterbook_id")+"' and t.f_meter_state != '已抄表' and t.f_meter_state != '冲正'";
            byte[] bts = data.getBytes("UTF-8");
            conn.setRequestProperty( "Content-Length", bts.length + "");
            conn.setUseCaches( false );
            conn.getOutputStream().write(bts);
            conn.getOutputStream().flush();

            InputStream is = conn.getInputStream();
            FileOutputStream fos = hybridActivity.openFileOutput("download.tmp", Context.MODE_PRIVATE);
            byte buf[] = new byte[1024];
            int bytesDownloaded = 0;
            do
            {
                int numread = is.read(buf);
                if (numread == -1)
                {
                    break;
                }
                bytesDownloaded += numread;
                publishProgress(new String[]{ 20 + "", "已下载：" + bytesDownloaded + "字节......"});
                fos.write(buf, 0, numread);
            }while(true);
            fos.close();

            publishProgress(new String[]{ 30 + "", "下载完成......"});
            BufferedReader br = new BufferedReader(new InputStreamReader(hybridActivity.openFileInput("download.tmp")));
            String text = br.readLine();
            br.close();

            //fuck for the illusion
            //删除hand plan表内相同册号的数据
            int n = new JSONArray(text).length();
            SqlService ss = new SqlService(hybridActivity);
            String meterbookid = new JSONArray(text).getJSONObject(0).getString("f_meterbook_id");
            String inputtor = new JSONArray(text).getJSONObject(0).getString("f_inputtor");
            ss.run("delete from t_handplan where f_meterbook_id='" + meterbookid + "'and f_inputtor='"+ inputtor + "'");
            JSONObject jo;
            for (int j = 1; j <=n ; j++) {
                jo =new JSONArray(text).getJSONObject(j-1);
                String userid = new JSONObject(jo.getString("userfile")).getString("f_user_id");
                ss.run("delete from t_userfiles where f_user_id='"+ userid + "'");
            }

            // 逐条保存抄表信息
            JSONObject savehandplan ;
            EntityService es = new EntityService(hybridActivity);

            publishProgress(new String[]{ 35 + "", "插入计划......"});

            for(int i = 1; i <= n; i++) {
                savehandplan = new JSONArray(text).getJSONObject(i-1);
                JSONObject userfilesid = new JSONObject(savehandplan.getString("userfile"));
                es.append("t_userfiles", userfilesid);
                savehandplan.put("f_savehangid",userfilesid.getString("f_user_id"));
                es.append("t_handplan", savehandplan);
                publishProgress(new String[]{ (35 + (i*65)/n ) + "", "插入计划项" + i + "/" + n});
            }
            conn.disconnect();
            publishProgress(new String[]{ 100 + "", "下载完成。"});
            return true;
        } catch(Exception e) {
            return false;
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        hybridActivity.createProgressDialog(ProgressDialog.STYLE_SPINNER);
    }

    @Override
    protected void onPostExecute(Boolean flag) {
        super.onPostExecute(flag);
        hybridActivity.closeProgress();
        hybridActivity.mWebView.loadUrl("javascript:HostApp.__callback__(" + index + ", " + flag + ","+ param +");");
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        int progress = Integer.parseInt(values[0]);
        hybridActivity.setProgress(progress, values[1]);
    }
}
